//
//  NSString+Validate.m
//  CategoryKit
//
//  Created by Horace on 16/12/6.
//  Copyright © 2016年 AiWays. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "NSString+Validate.h"

@implementation NSString (Validate)
/**
 *  Determines if string is not contains only whitespace and newlines
 */
- (BOOL)isNotEmpty
{
    NSString *trimmed = [self trimWhiteCharacters];
    return trimmed.length > 0;
}
/**
 *  trim whitespaces and newlines
 */
- (NSString *)trimWhiteCharacters
{
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
/**
 * Determines if the string contains only whitespace and newlines.
 */
///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)isWhitespaceAndNewlines
{
    NSCharacterSet *whitespace = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    for (NSInteger i = 0; i < self.length; ++i) {
        unichar c = [self characterAtIndex:i];
        if (![whitespace characterIsMember:c]) {
            return NO;
        }
    }
    return YES;
}

/**
 * Determines if the string is empty or contains only whitespace.
 */
///////////////////////////////////////////////////////////////////////////////////////////////////
- (BOOL)isEmptyOrWhitespace
{
    return !self.length || ![self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length;
}

/*
 * Checks to see if the string contains the given string, case insenstive
 */
- (BOOL)containsString:(NSString *)string
{
    return [self containsString:string options:NSCaseInsensitiveSearch];
}
/*
 * Checks to see if the string contains the given string while allowing you to define the compare options
 */
- (BOOL)containsString:(NSString *)string options:(NSStringCompareOptions)options
{
    return [self rangeOfString:string options:options].location == NSNotFound ? NO : YES;
}

/**
 校验字符串是否为手机号码

 @return BOOL
 */
- (BOOL)isMobileNumber
{
    if (!self || self.length <= 0) {
        return NO;
    }

    NSString *   regex     = @"^1\\d{10}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:self];
}
/**
 校验身份证信息

 @return BOOL
 */
- (BOOL)isIDCardNumber
{
    if (!self || self.length <= 0) {
        return NO;
    }

    NSString *cardRegex = @"[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1["
                          @"0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X|x)";
    NSPredicate *cardTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", cardRegex];
    return [cardTest evaluateWithObject:self];
}


/**
 校验是否是企业名称
 
 @return BOOL
 */
- (BOOL)isCompanyName {
    
    if (!self || self.length < 5 || self.length > 30) {
        return NO;
    }
    
    if ([self containsString:@"中国"] ||
        [self containsString:@"中华"] ||
        [self containsString:@"全国"] ||
        [self containsString:@"国家"] ||
        [self containsString:@"国际"]) {
        return NO;
    }
    
    if ([self isAllChinaChinese]) {
        return YES;
    }
    
    return NO;
}

/**
 校验是否是企业编号
 
 */
- (BOOL)isCompanyCode {
    
    NSString *match = @"[0-9A-Za-z]{18}";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
    
    return YES;
}

/**
 是否包含汉字
 
 */
- (BOOL)isContainsChinese
{
    NSRegularExpression *tNumRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[\u4e00-\u9fa5]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger tNumMatchCount = [tNumRegularExpression numberOfMatchesInString:self options:NSMatchingReportProgress range:NSMakeRange(0, self.length)];
    return tNumMatchCount > 0;
}

/**
 是否全部是汉字
 
 */
- (BOOL)isAllChinaChinese {
    
    NSString *match = @"(^[\u4e00-\u9fa5]+$)";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
    return [predicate evaluateWithObject:self];
}

/**
 是否包含数字

 */
- (BOOL)isContainsNumber {
    NSRegularExpression *tNumRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger tNumMatchCount = [tNumRegularExpression numberOfMatchesInString:self options:NSMatchingReportProgress range:NSMakeRange(0, self.length)];
    return tNumMatchCount > 0;
}

/**
 是否包含英文字符
 
 */
- (BOOL)isContainsEnglishCharacter {
    NSRegularExpression *tLetterRegularExpression =  [NSRegularExpression regularExpressionWithPattern:@"[A-Za-z]" options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString:self options:NSMatchingReportProgress range:NSMakeRange(0, self.length)];
    return tLetterMatchCount > 0;
}

/**
 校验是否可以拨电话

 @return BOOL
 */
- (BOOL)canTel
{
    if (!self || self.length <= 0) {
        return NO;
    }
    //    telStr = [telStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *telStr = [self trimWhiteCharacters];
    telStr           = [telStr stringByReplacingOccurrencesOfString:@"转" withString:@","];
    if (!(telStr && telStr.length)) {
        return NO;
    }
    if ([[UIApplication sharedApplication]
            canOpenURL:[NSURL URLWithString:[NSString stringWithFormat:@"telprompt://%@", telStr]]] == YES) {
        [[UIApplication sharedApplication]
            openURL:[NSURL URLWithString:[NSString stringWithFormat:@"telprompt://%@", telStr]]];
        return YES;
    }
    return NO;
}

/**
 校验是否为金额，保留小数点后两位

 @return BOOL
 */
- (BOOL)validateMoney
{
    NSString *   regex     = @"^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [predicate evaluateWithObject:self];
}

/**
 校验是否有emoji

 @return BOOL
 */
- (BOOL)stringContainsEmoji
{
    __block BOOL returnValue = NO;
    [self
        enumerateSubstringsInRange:NSMakeRange(0, [self length])
                           options:NSStringEnumerationByComposedCharacterSequences
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                          const unichar hs = [substring characterAtIndex:0];
                          if (0xd800 <= hs && hs <= 0xdbff) {
                              if (substring.length > 1) {
                                  const unichar ls = [substring characterAtIndex:1];
                                  const int     uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                  if (0x1d000 <= uc && uc <= 0x1f77f) {
                                      returnValue = YES;
                                  }
                              }
                          } else if (substring.length > 1) {
                              const unichar ls = [substring characterAtIndex:1];
                              if (ls == 0x20e3) {
                                  returnValue = YES;
                              }
                          } else {
                              if (0x2100 <= hs && hs <= 0x27ff) {
                                  returnValue = YES;
                              } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                  returnValue = YES;
                              } else if (0x2934 <= hs && hs <= 0x2935) {
                                  returnValue = YES;
                              } else if (0x3297 <= hs && hs <= 0x3299) {
                                  returnValue = YES;
                              } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 ||
                                         hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                  returnValue = YES;
                              }
                          }
                        }];
    return returnValue;
}

#define KPhoneRegex  @"\\d{3}-\\d{8}|\\d{3}-\\d{7}|\\d{4}-\\d{8}|\\d{4}-\\d{7}|1+\\d{10}|\\d{8}|\\d{7}"

- (NSArray<NSValue *> *)phoneRanges {
    
    NSError *error = NULL;
        // 根据匹配条件,创建了一个正则表达式(类方法,实例方法类似)
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:KPhoneRegex options:NSRegularExpressionCaseInsensitive error:&error];
    
    NSArray *match = [regex matchesInString:self
                                    options:NSMatchingReportCompletion
                                      range:NSMakeRange(0, [self length])];
    
    NSMutableArray *rangeArr = [NSMutableArray array];
    // 取得所有的NSRange对象
    if(match.count != 0)
    {
        for (NSTextCheckingResult *matc in match)
        {
            NSRange range = [matc range];
            NSValue *value = [NSValue valueWithRange:range];
            [rangeArr addObject:value];
        }
    }
    // 将要匹配的值取出来,存入数组当中
//    __block NSMutableArray *mulArr = [NSMutableArray array];
//    [rangeArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        NSValue *value = (NSValue *)obj;
//        NSRange range = [value rangeValue];
//        [mulArr addObject:[self substringWithRange:range]];
//    }];
    
    return rangeArr;
}

@end
